package com.example.waterdispenserm2.util;

import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import com.example.waterdispenserm2.bean.VideoInfo;
import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class GetVideo {
    //获取指定文件夹下所有视频文件
    public static ArrayList<VideoInfo> list = new ArrayList<>();
    private static String TAG="GetVideo";
    public static List<VideoInfo> getVideo() {
        list.clear();
        File file = MyLog.dirsFile;

        if (!file.exists()) {
            MyLog.e(TAG,"文件夹不存在");
            return null;
        }
        File[] subFile = file.listFiles();
        Log.d(TAG, "文件夹不存在");  //VID_20211229_074135.mp4
        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
            VideoInfo info = new VideoInfo(); //必须放在for循环里面，不然会显示几个一样的
// 判断是否为文件夹
            if (!subFile[iFileLength].isDirectory()) {
                String filename = subFile[iFileLength].getName();

                // 判断是否为MP4结尾
                if (filename.trim().toLowerCase().endsWith(".mp4") || filename.trim().toLowerCase().endsWith(".3gp") ||
                        filename.trim().toLowerCase().endsWith(".avi") || filename.trim().toLowerCase().endsWith(".flv")) {

                    // 设置文件路径
                    info.setPath(subFile[iFileLength].getPath());
                    Log.d(TAG, subFile[iFileLength].getPath()); ///storage/emulated/0/Android/data/com.example.video_list_demo1/cache/VID_20211229_074135.mp4

                    // 设置文件夹名称
                    info.setTitle(subFile[iFileLength].getName());
                     Log.d(TAG, subFile[iFileLength].getName());  //VID_20211229_074135.mp4

                    //设置文件时长
                    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                    retriever.setDataSource(subFile[iFileLength].getPath());
                    //得到的数除1000得到秒，再把秒分为时分秒
                    int time = Integer.parseInt(retriever.extractMetadata
                            (MediaMetadataRetriever.METADATA_KEY_DURATION)) / 1000;
                    info.setVideoTime(time);
                    Integer hour = time / 60 / 60;
                    Integer minutes = time / 60 % 60;
                    Integer remainingSeconds = time % 60;
                    String duration = hour + "时" + minutes + "分" + remainingSeconds + "秒";
                    info.setDuration(duration);


                    //根据路径获得视频缩略图
                    list.add( info);
                }
            }
        }
        return list;
    }
}

